<template>
    <div class="common-layout">
        <el-container>
            <el-main>
                <!-- 按钮组件 -->
                <div class="btn">
                    <div class="inp">
                        <el-select v-model="datas.status" clearable class="m-2" placeholder="请选择广告状态">
                            <el-option v-for="item in adStatusMap" :key="item.value" :label="item.name"
                                :value="item.value" />
                        </el-select>
                    </div>
                    <div class="inp">
                        <el-select v-model="datas.type" clearable class="m-2" placeholder="请选择广告类型">
                            <el-option v-for="item in adTypeMap" :key="item.value" :label="item.name"
                                :value="item.value" />
                        </el-select>
                    </div>
                    <el-button type="primary" :icon="Search" @click="init">查找</el-button>
                    <el-button type="primary" :icon="Plus" @click="add">添加</el-button>
                </div>
                <!-- 表格组件 -->
                <div id="tab">
                    <el-table :data="advertiseData" border width="100%">
                        <el-table-column prop="id" label="广告ID" align="center" />
                        <el-table-column prop="title" label="广告标题" align="center" />
                        <el-table-column label="广告图片" align="center" width="120px">
                            <!-- 悬停显示的图片 -->
                            <template #default="scope">
                                <el-tag type="info" v-if="scope.row.type == 6 || scope.row.type == 9">类型无需图片</el-tag>
                                <el-popover effect="light" trigger="hover" placement="top" width="24vw" v-else>
                                    <template #default>
                                        <span> <img :src="scope.row.imgUrl" style="width: 300px;" /></span>
                                    </template>
                                    <!-- 显示页面的图片 -->
                                    <template #reference>
                                        <span class="pic"> <img :src="scope.row.imgUrl" />
                                        </span>
                                    </template>
                                </el-popover>
                            </template>
                        </el-table-column>
                        <el-table-column prop="type" label="广告类型" align="center" width="140">
                            <template #default="scope">
                                <el-tag>{{ handlType(scope.row.type) }}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="status" label="广告状态" align="center">
                            <template #default="scope">
                                <el-tag :type="scope.row.status == 1 ? 'success' : 'danger'">{{ scope.row.status == 0
        ? '冻结' : '激活'
}}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="unionType" label="关联类型" align="center">
                            <template #default="scope">
                                <el-tag type="warning">
                                    {{ handleUnionTypes(scope.row.unionType) }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="unionValue" label="关联值[ID]" align="center" />
                        <el-table-column prop="gmtCreate" label="创建时间" align="center" />
                        <el-table-column label="操作" align="center" width="200">
                            <template #default="scope">
                                <el-button type="primary" @click="handlEdit(scope.row)">编辑</el-button>
                                <el-button type="danger" @click="handlDelt(scope.$index, scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <!-- 分页组件 -->
                <Pagination @page-change="handlePagehange" v-bind="datas" />
                <!-- 对话框 -->
                <el-dialog v-model="dialogFormVisible" :title="bool ? '创建' : '编辑'" destroy-on-close
                    style="width: 40vw;">
                    <el-form :model="form" ref="ruleFormRef" :rules="rules">
                        <el-form-item label="广告标题" prop="title" label-width="130">
                            <el-input v-model="form.title" autocomplete="off" />
                        </el-form-item>
                        <el-form-item label="广告类型" prop="type" label-width="130">
                            <el-select v-model="form.type" placeholder="请选择" clearable @change="changes">
                                <el-option v-for="item in adTypeMap" :key="item.value" :label="item.name"
                                    :value="item.value" @click="changePic(item)" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="广告图片" prop="imgUrl" v-show="requireds" id="uploadImg" label-width="130"
                            :style="{ background: form.color }">
                            <el-upload class="avatar-uploader" action="http://192.168.1.188:8989/upload/admin"
                                :show-file-list="false" :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload" :headers="headers">
                                <img v-if="form.imgUrl" :src="form.imgUrl" class="avatar" />
                                <el-icon v-else class="avatar-uploader-icon">
                                    <Plus />
                                </el-icon>
                            </el-upload>
                        </el-form-item>
                        <el-form-item label="广告状态" prop="status" label-width="130">
                            <el-switch v-model="form.status" class="ml-2" :active-value=1 :inactive-value=0
                                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" />
                        </el-form-item>
                        <el-form-item label="关联类型" prop="unionType" label-width="130">
                            <el-select v-model="form.unionType" :placeholder="form.type ? '点击跳转类型' : '请先选择广告类型'"
                                clearable>
                                <el-option v-for="item in adUinonTypeMap"
                                    :disabled="!valuedata || !valuedata.unionTypes?.includes(item.value)"
                                    :key="item.value" :label="item.name" :value="item.value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="商品" prop="unionValue" v-if="form.unionType === 1 ? true : false"
                            label-width="130">
                            <el-cascader v-model="form.unionValue" :options="productList" @change="changeOptins"
                                :props="{ emitPath: true, label: 'label', value: 'id', children: 'children' }"
                                placeholder="关联至商品" filterable />
                        </el-form-item>
                        <el-form-item label="类目" prop="unionValue" v-if="form.unionType === 2" label-width="130">
                            <div class="m-4">
                                <el-cascader v-model="form.unionValue" :options="category" @change="changeOptins"
                                    :props="{ checkStrictly: true, label: 'title', value: 'id', children: 'childrenList' }" />
                            </div>
                        </el-form-item>
                        <el-form-item label="关键字" prop="unionValue" v-if="form.unionType === 3" label-width="130">
                            <el-input v-model="form.unionValue" autocomplete="off"
                                placeholder="点击广告后,用户将得到此关键字的商品搜索结果" />
                        </el-form-item>
                        <el-form-item label="功能页面" prop="unionValue" v-if="form.unionType === 4" label-width="130">
                            <el-select v-model="form.unionValue" placeholder="请选择一个功能页面" clearable>
                                <el-option v-for="item in functionPages" :key="item.value" :label="item.name"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-form>
                    <template #footer>
                        <span class="dialog-footer">
                            <el-button @click="dialogFormVisible = false">取消</el-button>
                            <el-button type="primary" @click="confirm(ruleFormRef)">
                                确定
                            </el-button>
                        </span>
                    </template>
                </el-dialog>
            </el-main>
        </el-container>
    </div>
</template>
<script lang="ts" setup>
import type { User, advs } from '@/type/params'//引入类型
import { ref, onMounted, reactive, computed } from 'vue'//引入响应式，生命周期
import { Search, Plus } from '@element-plus/icons-vue'//引入图标
import { post } from '@/untils/request'//引入请求方式
import Pagination from '@/components/Pagination.vue' //引入分页组件
import { friendlyDates } from '@/time/friendlTime'//引入友好日期
import { canvasImgColor } from '@/handle/theColorFn'//引入获取图片平均色
import { ElMessage } from 'element-plus'//引入消息提示框
import type { FormInstance, UploadProps } from 'element-plus' //引入element-plus框架
import cookie from 'js-cookie'

const ruleFormRef = ref<FormInstance>()
const requireds = ref(false)//requireds标识判断是否显示上传图片组件
const bool = ref(false)//bool标识判断添加/编辑
const dialogFormVisible = ref(false)//显示/隐藏弹框
const advertiseData = ref([])//广告管理列表
const category = ref([])//类目列表
const productList = ref([])//商品列表
const datas = ref({//渲染页面数据
    total: 0,
    pageNo: 1,//当前页面
    pageSize: 10,//一页面所显示的条数
    _gp: 'admin.advert',
    _mt: 'list',
    status: undefined,
    type: undefined
})
//广告关联类型
const adUinonTypeMap = [
    { value: 1, name: '商品' },
    { value: 2, name: '类目' },
    { value: 3, name: '关键字' },
    { value: 4, name: '功能页面' },
]
//广告类型
const adTypeMap = [
    { value: 1, unionTypes: [1, 2, 3, 4], picRequire: true, name: '轮播' },
    { value: 2, unionTypes: [2], picRequire: true, name: '分类精选' },
    { value: 3, unionTypes: [1, 2, 3, 4], picRequire: true, name: '横幅' },
    { value: 4, unionTypes: [1, 2, 3, 4], picRequire: true, name: '首页轮播下5按钮' },
    { value: 6, unionTypes: [1, 2, 3, 4], picRequire: false, name: '公告' },
    { value: 9, unionTypes: [1], picRequire: false, name: '商品推荐' },
]
const functionPages = [
    { value: '/pages/product/groupshop', name: '团购列表' },
    { value: '/pages/coupon/list', name: '优惠券列表' },
]

//广告状态
const adStatusMap = [
    { value: 0, name: '冻结' },
    { value: 1, name: '激活' },
]
//表单数据
const form = ref<advs>({
    title: '',//广告名称
    adId: 0,//广告id
    type: undefined,//广告类型
    status: 0,//广告状态
    imgUrl: '',//广告图片
    color: '',//颜色
    unionType: undefined,//关联类型
    unionValue: ''//关联值
})
//清空后的表单数据
const clerrForm = ref<advs>({
    title: '',
    adId: 0,
    type: undefined,
    status: 0,
    imgUrl: '',
    color: '',
    unionType: undefined,
    unionValue: ''
})
//生命周期---挂载后
onMounted(() => {
    init()
})
//渲染
function init() {
    post(datas.value).then(res => {//渲染广告管理列表
        let { items } = res.data
        let { data } = res
        advertiseData.value = items//赋值
        datas.value.total = data.total//赋值总条数
        advertiseData.value.map((item: any) => {//映射友好日期
            item.gmtCreate = friendlyDates(item.gmtCreate)
            return item
        })
    }).catch(err => {
        console.log(err);
    })

    const categorys = reactive({
        _gp: 'admin.category',
        _mt: 'categoryTree',
    })
    post(categorys).then(res => {//渲染类目列表
        category.value = res.data
    }).catch(err => {
        console.log(err);

    })
    const products = reactive({
        _gp: 'admin.product',
        _mt: 'getSpuBigTree',
    })
    post(products).then(res => {//渲染类目列表
        productList.value = res.data
    }).catch(err => {
        console.log(err);

    })
};
//存储请求头
const headers = reactive({
    AdminToken: cookie.get('token')
})
//上传图片--获取图片平均色
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
    if (200 == response.errno) {
        form.value.imgUrl = response.url // 得到上传图片成功的路径
        canvasImgColor(form.value.imgUrl, (e: string) => {
            form.value.color = e
        })
    }
}

//处理上传图片的条件
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('Avatar picture must be JPG format!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
    return true
}

//处理是否显示上传图片组件事件
function changePic(row: any) {
    requireds.value = row.picRequire
}
//数据处理类目列表--截取id
function changeOptins(value: any) {
    form.value.unionValue = value.slice(-1)[0]
}
// 广告类型禁用
const valuedata = computed(() => {
    if (form.value.type) {
        return adTypeMap.find(item => item.value == form.value.type)
    } else {
        return ''
    }
})
//添加
function add() {
    bool.value = true//bool为true进入添加框
    dialogFormVisible.value = true//显示对话框
    Object.assign(form.value, clerrForm.value)//合并表单数据与清空后的表单数据
    requireds.value = false
}
//处理广告类型赋值为空
function changes() {
    form.value.unionType = undefined
}

//编辑
function handlEdit(row: User) {
    console.log(row);
    bool.value = false//bool为false进入编辑框
    dialogFormVisible.value = true//显示对话框
    form.value.adId = row.id
    if (1 == row.unionType || 2 == row.unionType) {
        row.unionValue = +row.unionValue//选择类目时数字转换字符串
    }
    Object.assign(form.value, row)//合并对象
}
//弹框确定按钮
function confirm(formEl: FormInstance | undefined) {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            if (bool.value == true) {
                let adds = {
                    _gp: 'admin.advert',
                    _mt: 'create',
                    ...form.value
                }
                post(adds).then(res => {
                    let { errno, errmsg } = res
                    if (200 == errno) {
                        ElMessage.success('添加成功')
                        dialogFormVisible.value = false//隐藏对话框
                        init()//刷新
                    } else {
                        ElMessage.error(errmsg)
                    }
                }).catch(err => {
                    console.log(err);
                    ElMessage.info('添加失败')
                })
            } else if (bool.value == false) {
                let edits = {
                    _gp: 'admin.advert',
                    _mt: 'edit',
                    ...form.value
                }
                post(edits).then(res => {
                    console.log(res);
                    ElMessage.success('编辑成功')
                    dialogFormVisible.value = false//隐藏对话框
                    init()//刷新

                }).catch(err => {
                    console.log(err);
                    ElMessage.info('编辑失败')
                })
            }
        } else {
            return false
        }
    })
}
//非空验证
const rules = reactive({
    title: [{ required: true, trigger: 'blur', message: "广告标题不能为空" }],
    type: [{ required: true, trigger: 'change', message: "广告类型不能为空" }],
    status: [{ required: true, trigger: 'change', message: "广告状态不能为空" }],
    unionType: [{ required: true, trigger: 'change', message: "关联类型不能为空" }],
})

//删除
function handlDelt(index: number, row: User) {
    console.log(row);
    const datasDlet = {//删除角色管理数据
        _gp: 'admin.advert',
        _mt: 'delete',
        type: row.type,
        adId: row.id,//将当前对象的id赋值给角色id(roleId)
    }
    //@ts-ignore
    ElMessageBox.confirm(
        '确定要删除吗?',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消'
        }
    )
        .then(() => {
            post(datasDlet).then(res => {
                console.log(res);
                advertiseData.value.splice(index, 1)//点击确定进入请求，请求成功删除当前行
                ElMessage.success('删除成功')
            }).catch(err => {
                console.log(err);
                ElMessage.info('删除失败')
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })

}
//判断状态--关联类型
function handleUnionTypes(unionTypes: number) {
    if (unionTypes == 1) {
        return '类目';
    } else if (unionTypes == 2) {
        return '商品';
    } else if (unionTypes == 3) {
        return '功能页面';
    }
    else if (unionTypes == 4) {
        return '关键字';
    }
}
//判断状态--公告类型类型
function handlType(type: number) {
    if (type == 1) {
        return '轮播';
    } else if (type == 2) {
        return '分享精选';
    } else if (type == 3) {
        return '横幅';
    }
    else if (type == 4) {
        return '首页轮播下5按钮';
    } else if (type == 6) {
        return '公告';
    }
    else if (type == 9) {
        return '商品推荐';
    }
}
//分页
function handlePagehange(s: { page: number, limit: number }) {
    datas.value.pageNo = s.page
    datas.value.pageSize = s.limit
    init()
}

</script>
<style lang="less" scoped>
.el-container {
    .btn {
        width: 100%;
        display: flex;

        .inp {
            width: 200px;
            margin-right: 15px;
        }
    }

    .btn,
    #tab {
        margin-bottom: 20px;
    }

    #tab {
        .pic {
            img {
                width: 30px;
                height: 30px;
                vertical-align: middle;
            }
        }
    }

    .avatar-uploader .avatar {
        width: 178px;
        height: 178px;
        display: block;

    }

}
</style>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>